package com.zhongshengnetwork.rightbe.lang.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
//import android.support.annotation.NonNull;
//import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BaseAnalyticsFragment;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.pulluprefresh.xlistview.XListView;
import com.zhongshengnetwork.rightbe.gsonmodel.CircleLangModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.LangPublishActivity;
import com.zhongshengnetwork.rightbe.lang.activity.UserLangActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by luojingxing on 2018/6/14.
 */

public class CareOrFansFragment extends BaseAnalyticsFragment {
    public int pageindex = 0;
    public static final int Records = 20;
    private boolean isHasMore = false;
    private List<CircleLangModel> list;
    private ListView listview;
    private MyAdapter adapter;
    private View rootView;//缓存Fragment view
    public int type = 0;
    private ImageView no_data_img;
    private RefreshLayout mRefreshLayout;

    private EditText search_edit;
    private Button search_button;
    private String nickname = "";

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden){
            hintKeyBoard();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.care_fan_layout, container, false);
            if (list == null){
                list = new ArrayList<CircleLangModel>();
            }
            search_edit = (EditText) rootView.findViewById(R.id.search_edit);
            search_edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                    if (i == EditorInfo.IME_ACTION_SEARCH) {
                        String search = search_edit.getText().toString().trim();
                        onClickSearch(textView);
                        return true;
                    }
                    return false;
                }
            });
            search_button = (Button) rootView.findViewById(R.id.search_button);
            search_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickSearch(v);
                }
            });
            pageindex = 0;
            no_data_img = (ImageView)rootView.findViewById(R.id.no_data_img);
            no_data_img.setVisibility(View.VISIBLE);
            listview=(ListView) rootView.findViewById(R.id.circle_lang_listview);
            adapter=new MyAdapter();
            listview.setAdapter(adapter);
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    hintKeyBoard();
                    Log.e("TAG","position="+position);
                    if (getActivity() == null){
                        return;
                    }
                    int index = position;//-1;
                    while (index < 0){//解决部分手机点击第一条不是从1开始的问题
                        index+=1;
                    }
                    CircleLangModel model = list.get(index);
                    Intent intent = new Intent(getActivity(), UserLangActivity.class);
                    intent.putExtra(APIKey.useridKey,model.getUserid());
                    intent.putExtra(APIKey.typeKey,1);
                    intent.putExtra(APIKey.titleKey,model.getNickname());
                    startActivity(intent);
                }
            });
            listview.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView absListView, int i) {
                    if (i == SCROLL_STATE_FLING ||
                            i == SCROLL_STATE_TOUCH_SCROLL){
                        hintKeyBoard();
                    }
                }

                @Override
                public void onScroll(AbsListView absListView, int i, int i1, int i2) {

                }
            });

            mRefreshLayout = rootView.findViewById(R.id.refreshLayout);
            //设置 Header 为 贝塞尔雷达 样式
            mRefreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setEnableHorizontalDrag(true));//BezierRadarHeader
            //设置 Footer 为 球脉冲 样式
            mRefreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
            mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
            mRefreshLayout.setEnableRefresh(true);//启用刷新
            mRefreshLayout.setEnableLoadMore(true);//启用加载
            //刷新
            mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    //refreshlayout.finishRefresh();
                    pageindex = 0;
                    getData();
                }
            });
            mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                    //refreshLayout.finishLoadMore();
                    getData();
                }
            });

            RelativeLayout care_fan_layout = (RelativeLayout) rootView.findViewById(R.id.care_fan_layout);
            care_fan_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            listview.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
            search_edit.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
            search_edit.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            RelativeLayout search_top = (RelativeLayout) rootView.findViewById(R.id.search_top);
            search_top.setBackgroundColor(AppThemeUtils.getInstance().getSearchBgColor());
            RelativeLayout search_shape_layout = (RelativeLayout) rootView.findViewById(R.id.search_shape_layout);
            search_shape_layout.setBackgroundResource(AppThemeUtils.getInstance().getSearchBackground());

            getFirstData(false);
        }else {
            //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
            final ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
            getFirstData(false);
        }
        return rootView;
    }

    public void getFirstData(boolean isFirst){
        if (CommonUtils.isLogin() == false){
            return;
        }
        if (listview == null || list == null){
            return;
        }
        if (list.size() == 0){
            //listview.startRefresh();
            if (mRefreshLayout != null){
                pageindex = 0;
                mRefreshLayout.autoRefresh();
            }
        }else {
            if (isFirst == true){
                //listview.smoothScrollToPosition(0);
                listview.setSelection(0);
            }
        }
    }

    protected Map<String, String> getHttpParams() {
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        map.put(APIKey.typeKey,type+"");
        map.put("pageindex",pageindex+"");
        map.put("pagerecords",Records+"");
        map.put("name",CommonUtils.formatString(nickname));
        return map;
    }

    protected String getHttpPath() {
        return "miniapp/langappid/carelist.do";
    }

    private void getData(){
        if (listview == null){
            return;
        }

        if (search_edit != null){
            if (search_edit.getText() != null){
                String text = search_edit.getText().toString();
                nickname = text;
            }else {
                nickname = "";
            }
        }

        new Thread(){
            @Override
            public void run() {
                super.run();
                HttpsUtils.miniAppDo(getHttpParams(), getHttpPath() , new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        if (getActivity() != null){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                        list.clear();
                                    }
                                    CommonModel commonModel = GsonTools.getCommonModel(data);
                                    if (commonModel.getFlag().equals("1")){
                                        List<CircleLangModel> l = GsonTools.getCircleLangModel(data);
                                        if (l != null && l.size() > 0){
                                            no_data_img.setVisibility(View.INVISIBLE);
                                            if (l.size() >= Records){
                                                //listview.setPullLoadEnable(true);
                                                mRefreshLayout.setEnableLoadMore(true);
                                            }else {
                                                //listview.setPullLoadEnable(false);
                                                mRefreshLayout.setEnableLoadMore(false);
                                            }
                                            list.addAll(l);
                                        }else {
                                            isHasMore = false;
                                            //listview.setPullLoadEnable(false);
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        adapter.notifyDataSetChanged();
                                        if (pageindex == 0){
                                            //listview.smoothScrollToPosition(0);
                                            listview.setSelection(0);
                                        }
                                        pageindex += 1;
                                    }else {
                                        CustomApplication.showTip(commonModel, getActivity());
                                    }
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        if (getActivity() != null){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                    }
                                }
                            });
                        }
                    }
                });
            }
        }.start();

    }


    public void hintKeyBoard() {
        if (getActivity() == null){
            return;
        }
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getActivity().getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getActivity().getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    private void onClickSearch(View view){
        hintKeyBoard();
        String text = search_edit.getText().toString();
        nickname = text;
        if (mRefreshLayout != null){
            Log.e("TAG","进来获取数据了刷新界面");
                /*
                @param delayed 开始延时
                @param duration 拖拽动画持续时间
                @param dragRate 拉拽的高度比率（要求 ≥ 1 ）
                */
            mRefreshLayout.autoRefresh(100,300,1f,false);
        }
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }


        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            //convertView的复用
            if (convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.lang_circle_item,null);
            }
            View view=convertView;
            //view = LayoutInflater.from(getActivity()).inflate(R.layout.lang_circle_item, null);

            RelativeLayout lang_circle_item_layout = (RelativeLayout) view.findViewById(R.id.lang_circle_item_layout);
            lang_circle_item_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            LinearLayout lang_circle_line = (LinearLayout) view.findViewById(R.id.lang_circle_line);
            lang_circle_line.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());


            ImageView lang_circle_header = (ImageView) view.findViewById(R.id.lang_circle_header);
            ImageView privateIcon = (ImageView) view.findViewById(R.id.private_icon);
            TextView lang_circle_nickname = (TextView) view.findViewById(R.id.lang_circle_nickname);
            lang_circle_nickname.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            Button lang_circle_care = (Button) view.findViewById(R.id.lang_circle_care);
            TextView lang_circle_smart_value = (TextView) view.findViewById(R.id.lang_circle_smart_value);
            TextView lang_circle_count = (TextView) view.findViewById(R.id.lang_circle_count);
            TextView lang_comment_count = (TextView) view.findViewById(R.id.lang_comment_count);
            TextView lang_circle_care_count = (TextView) view.findViewById(R.id.lang_circle_care_count);
            CircleLangModel model = list.get(position);

            Glide.with(getActivity()).load(model.getHeader()).transform(new CircleTransform(getActivity())).dontAnimate().into(lang_circle_header);

            if (!CommonUtils.isEmpty(model.getPrivateIcon())){
                privateIcon.setVisibility(View.VISIBLE);
                Glide.with(getActivity()).load(model.getPrivateIcon()).transform(new CircleTransform(getActivity())).dontAnimate().into(privateIcon);
            }else {
                privateIcon.setVisibility(View.GONE);
            }

            lang_circle_nickname.setText(model.getNickname());
            lang_circle_care.setTag(position);
            if (model.iscare() == true){
                lang_circle_care.setVisibility(View.INVISIBLE);
            }else {
                lang_circle_care.setVisibility(View.VISIBLE);
                lang_circle_care.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        hintKeyBoard();
                        onClickCare((int)v.getTag());
                    }
                });
            }
            lang_circle_smart_value.setText(CommonUtils.getDisplayCount(model.getLevel())+"");
            lang_circle_count.setText((model.getLangcount()-model.getLifecount())+"");
            lang_comment_count.setText(model.getWeishucount()+"");
            lang_circle_care_count.setText(model.getFanscount()+"");

            ImageView lang_member_icon = (ImageView) view.findViewById(R.id.lang_member_icon);
            if (!CommonUtils.isEmpty(model.getMemberIcon())){
                lang_member_icon.setVisibility(View.VISIBLE);
                try{
                    Glide.with(getActivity()).load(model.getMemberIcon()).
                            diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(lang_member_icon);
                }catch (Exception e){
                    LangPublishActivity.uploadError("智慧排行点赞列表加载图片报错："+e.getLocalizedMessage());
                }

            }else {
                lang_member_icon.setVisibility(View.INVISIBLE);
            }

            return view;
        }

        //点击关注
        private void onClickCare(final int position){
            if (getActivity() == null){
                return;
            }
            if (CommonUtils.isLogin() == false){
                Intent intent = new Intent(getActivity(),LoginActivity.class);
                startActivity(intent);
                return;
            }
            final CircleLangModel model = list.get(position);
            if (model.iscare() == true){
                return;
            }
            model.setIscare(true);
            list.set(position,model);
            adapter.notifyDataSetChanged();

            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put("authorid", model.getUserid());
            String url = "miniapp/"+"langappid"+"/addcare.do";
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                }

                @Override
                public void onError(String msg) {
                }
            });

    }

}}
